# _*_ coding: utf-8 _*_
# @创建时间：2023/4/29 23:18
# @作者：dengqihua
# @名称 : dependencies.py
# @描述 : 依赖项

from typing import List

from fastapi import HTTPException, Header, Query, Request, status

from app.libs.utils import success_response


async def auth_token_header(user_token: str = Header(..., description='用户token'), request: Request = Request):
    try:
        from app.logic.user_logic import UserLogic
        user_info = await UserLogic.get_user_info_by_token(user_token)
        if not user_info:
            raise Exception('用户登录token不存在或已过期！')

        request.state.user = user_info
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail={'code': 40100, 'message': "用户登录token不存在或已过期！"}
        )


class Paginator:
    """分页器"""

    def __init__(
            self,
            page: int = Query(1, description="页码，默认第一页", ge=1),
            limit: int = Query(20, description="每页显示条数，默认20", le=500)
    ):
        self.page = page
        self.offset = (page - 1) * limit
        self.limit = limit

    def get_list_response(self, data_list: List, total=None, do_format=False):
        """获取分页响应"""
        data = self.get_page_data(data_list, total)
        return success_response(data, do_format=do_format)

    def get_page_data(self, data_list: List, total=None):
        next_offset = self.offset + self.limit

        assert isinstance(total, int)
        next_offset = next_offset if next_offset < total else total
        has_more = total > next_offset
        data = {
            "data_list": data_list,
            "total": total,
            "has_more": has_more,
            "next_offset": next_offset
        }
        return data
